package com.atshiyou.servlet;

import com.atshiyou.webDatabase.ConnectMysql;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(value = "/recharge")
public class RechargeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = (String) req.getSession().getAttribute("username");
        String pointNum = req.getParameter("pointNum");
        System.out.println("查询到的充值积分:"+pointNum);
        int i = Integer.parseInt(pointNum);
        System.out.println("获取到用户输入的充值金额:"+i);
        //先获取未充值之前的积分

        int oldPoint = (int) req.getSession().getAttribute("userPoint");
        System.out.println("获取到用户原本的金额:"+oldPoint);
        int updatePoint = oldPoint+i;

        try {
            //更新数据库的充值之后的积分信息
            boolean b = ConnectMysql.updatePoint(username, updatePoint);
            if(b){
                System.out.println("充值到账");
            }else{
                System.out.println("充值失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //为了避免充值失败，所以我们再次查询数据库，获取积分值
        int newPoint= 0;
        try {
            newPoint = ConnectMysql.findPoint(username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(newPoint != oldPoint) {
            req.getSession().setAttribute("userPoint", newPoint);
            PrintWriter printWriter = resp.getWriter();
            printWriter.write("<script>alert('恭喜您，充值成功');location.href='./chargePage.jsp'</script>");
        }else{
            PrintWriter printWriter = resp.getWriter();
            printWriter.write("<script>alert('不好意思，充值失败');location.href='./chargePage.jsp'</script>");
        }


    }
}
